<template>
  <div class="content-container" v-loading="state.pageLoading">
    <div class="item-header">
      <HBreadcrumb :routes="breadcrumbRoutes"></HBreadcrumb>
    </div>
    <div class="item-content">
      <el-form class="room-form" :rules="roomRules" ref="roomFormRef" :model="form" label-width="auto">
        <el-form-item label="房源名称" prop="roomName">
          <el-input v-model.trim="form.roomName" placeholder="如：××市××小区××栋××室" clearable/>
        </el-form-item>
        <el-form-item label="房源地址" prop="address">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" v-model.trim="form.address" placeholder="如：××省××市××区××街道××小区××栋××室" clearable/>
        </el-form-item>
        <el-form-item label="房源类型" prop="roomType">
          <el-radio-group v-model="form.roomType">
            <el-radio-button v-for="item in roomTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-select v-model="form.city" placeholder="请选择" clearable>
            <el-option v-for="item in cityOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="房东" prop="ownerId">
          <el-select v-model="form.ownerId" placeholder="请选择" clearable :loading="ownerListLoading">
            <el-option v-for="item in ownerList" :key="item" :label="item.id" :value="item.id" />
          </el-select>
          <span class="add-owner">
            若无该房东，可点击此处
            <el-button class="add-owner-btn" type="primary" link @click="addOwner">添加</el-button>
            成功后再选择
          </span>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" v-model.trim="form.remark" placeholder="请输入备注" clearable/>
        </el-form-item>
        <el-form-item label="推荐指数" prop="rate">
          <el-rate :colors="elRateColor" v-model="form.rate" allow-half clearable/>
        </el-form-item>
      </el-form>
      <div class="btn-group">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" :loading="state.submitLoading" @click="validateForm">提交</el-button>
      </div>
    </div>
    <AddEditOwnerDialog ref="addEditOwnerDialogRef"> </AddEditOwnerDialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { roomTypeOptions, elRateColor } from '@/assets/js/enum'
import { useRoute, useRouter } from 'vue-router'
import AddEditOwnerDialog from '@/components/ownerManage/addEditOwner.vue'
import { roomStore, ownerStore} from '@/stores'
import { ElMessage } from 'element-plus'
import type { Owner } from '@/api/owner/types'

const route = useRoute()
const router = useRouter()
const useRoomStore = roomStore()
const useOwnerStore = ownerStore()

const breadcrumbRoutes = [
  { 
    path: '/admin/roomManage/list',
    label: '房源管理'
  },
  { 
    path: '',
    label: route.query.roomId ? '编辑房源' : '新增房源'
  }
]

const roomFormRef = ref()
const form = reactive({
  roomName: '',
  address: '',
  roomType: '',
  city: '',
  ownerId: '',
  remark: '',
  rate: 0
})

const state = reactive({
  submitLoading: false,
  pageLoading: false
})

const roomRules = {
  roomName: [
    { required: true, message: '请输入房源名称', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入房源地址', trigger: 'blur' }
  ],
  roomType: [
    { required: true, message: '请选择房源类型', trigger: 'change' }
  ],
  city: [
    {required: true, message: '请选择城市', trigger: 'change'}
  ],
  ownerId: [
    {required: true, message: '请选择房东', trigger: 'change'}
  ],
  remark: [
    {required: false, message: '请输入备注', trigger: 'blur'}
  ],
  rate: [
    {required: false, message: '请选择推荐指数', trigger: 'change'}
  ]
}

const cityOptions = [
  {
    value: '1',
    label: '北京'
  },
  {
    value: '2',
    label: '上海'
  },
  {
    value: '3',
    label: '广州'
  }
]

// 表单验证
const validateForm = () => {
  roomFormRef.value.validate(valid => {
    if (valid) {
      route.query.roomId ? editRoomInfo() : addRoomInfo()
    } else {
      return false
    }
  })
}
// 新增房源信息
const addRoomInfo = () => {
  state.submitLoading = true
  let params = { ...form }
  useRoomStore.addRoomInfo(params).then(res => {
    if (res.state === 'OK') {
      ElMessage.success('新增房源成功')
      router.push({
        name: 'roomManageList'
      })
    } else {
      ElMessage.error(res.errorMessage || '新增房源失败')
    }
  })
  .catch(error => {
    ElMessage.error(error.errorMessage || '新增房源失败')
  })
  .finally(() => {
    state.submitLoading = false
  })
}

// 编辑房源信息
const editRoomInfo = () => {
  state.submitLoading = true
  let params = { ...form }
  useRoomStore.editRoomInfo(params).then(res => {
    if (res.state === 'OK') {
      ElMessage.success('编辑房源成功')
      router.push({
        name: 'roomManageList'
      })
    } else {
      ElMessage.error(res.errorMessage || '编辑房源失败')
    }
  })
  .catch(error => {
    ElMessage.error(error.errorMessage || '编辑房源失败')
  })
  .finally(() => {
    state.submitLoading = false
  })
}
const cancel = () => {
  router.push({
    name: 'roomManageList'
  })
}


// 获取房东列表
const ownerList = ref<Owner[]>()
const ownerListLoading = ref<boolean>(false)
const getOwnerList = () => {
  ownerListLoading.value = true
  const params = {
    
  }
  useOwnerStore.getAllOwnerList(params).then((res: any) => {
    const { state, body } = res
    if (state === 'OK') {
      ownerList.value = body.content || []
      // ownerListPage.total = body.total || 0
    } else {
      ElMessage.error(res.errorMessage || '获取房东列表失败')
    }
  })
  .catch((err: any) => {
    ElMessage.error(err.errorMessage || '获取房东列表失败')
  })
  .finally(() => {
    ownerListLoading.value = false
  })
}

// 新增房东信息
const addEditOwnerDialogRef = ref()
const addOwner = () => {
  addEditOwnerDialogRef.value.openDialog()
}

const getRoomDetail = () => {
  useRoomStore.getRoomDetail().then(res => {
    if (res.state === 'OK') {
      // TODO: 回显数据
    } else {
      ElMessage.error(res.errorMessage || '获取房源详情异常')
    }
  })
  .catch(error => {
    ElMessage.error(error.errorMessage || '获取房源详情异常')
  })
}

onMounted(() => {
  route.query.roomId && getRoomDetail()
  getOwnerList()
})
</script>
<style lang="scss" scoped>
.content-container {
  .item-content {
    .room-form {
      .el-input, .el-textarea {
        width: 360px;
      }
      .el-select {
        width: 200px;
      }
      .add-owner {
        font-size: 12px;
        margin-left: 10px;
        .add-owner-btn {
          font-size: 12px;
          cursor: pointer;
          text-decoration: underline;
        }
      }
    }
    .btn-group {
      margin-left: 80px;
    }
  }
}
</style>
